#!/bin/sh

PATH=/snap/bin:$PATH

# microk8s is required.
if ! which microk8s.kubectl; then
    echo "microk8s is not installed."
    exit 0
fi

if ! which timeout; then
    echo "timeout is not installed."
    exit 0
fi

container_cmd=microk8s.ctr
image_arg="--namespace k8s.io images"
if ! which $container_cmd; then
    container_cmd=microk8s.docker
    image_arg=image
    if ! which $container_cmd; then
        echo "Neither docker or ctr image control found."
        exit 0
    fi
fi

# We will give up if below steps can not be finished in 110s because snapd will kill us in 120s.
# It's not an install/refresh blocker if we can't get the images.
timeout 110s sh <<EOT || echo "Timed out waiting to install microk8s image."

echo "Wait for microk8s to be ready if needed."
microk8s.status --wait-ready --timeout 30 2>&1
juju_version=\$(/snap/bin/juju version | rev | cut -d- -f3- | rev)
oci_image="ghcr.io/juju/jujud-operator:\$juju_version"
mongo_image="ghcr.io/juju/juju-db:4.4"

echo "Going to cache images: \$oci_image and \$mongo_image."
echo "Pulling: \$oci_image."

$container_cmd $image_arg list | grep \$oci_image || $container_cmd $image_arg pull \$oci_image || true
echo "Pulling: \$mongo_image."
$container_cmd $image_arg list | grep \$mongo_image || $container_cmd $image_arg pull \$mongo_image || true
EOT
